package io.github.idol.data
import android.text.TextUtils
import com.blankj.utilcode.util.SPUtils
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import io.github.idol.Constants
import io.github.idol.HeaderInterceptor
import io.reactivex.Flowable
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

/**
 * Created by codeczx on 2018/7/30 下午 09:33.
 * Class description:
 */

class ApiRepository private constructor(){

    private val userApi: ApiService by lazy(mode=LazyThreadSafetyMode.SYNCHRONIZED){
        val retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(USER_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
        retrofit.create(ApiService::class.java)
    }

    private val roomApi: ApiService by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
        val retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ROOM_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
        retrofit.create(ApiService::class.java)
    }

    fun login(username:String,password:String):Flowable<LoginInfo>{
        val loginRequestBody = LoginRequestBody(0, 0, password, username)
        return userApi.login(loginRequestBody)
    }

    fun getRoomList():Flowable<RoomListInfo>{
        val spUtils = SPUtils.getInstance(Constants.SP_NAME)
        val friendsStr = spUtils.getString(Constants.SP_FRIENDS,"")
        val friends:ArrayList<Int> = if(TextUtils.isEmpty(friendsStr)){
            ArrayList()
        }else{
            val listType = object : TypeToken<ArrayList<Int>>(){}.type
            Gson().fromJson(friendsStr,listType)
        }


        val roomListRequestBody = RoomListRequestBody(friends)
        return roomApi.getRoomList(roomListRequestBody)
    }

    fun getRoomDetail(roomId:Int,lastTime:Long):Flowable<RoomDetailInfo>{
        val roomDetailRequestBody = RoomDetailRequestBody(roomId, 0,lastTime,20)
        return roomApi.getRoomDetail(roomDetailRequestBody)
    }

    companion object {

        const val IMAGE_BASE_URL = "https://source.48.cn/"
        private const val ROOM_BASE_URL = "https://pjuju.48.cn/"
        private const val USER_BASE_URL = "https://puser.48.cn/"



        val INSTANCE: ApiRepository by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            ApiRepository()
        }

        private val okHttpClient: OkHttpClient
        get() = OkHttpClient.Builder()
                .addInterceptor(HeaderInterceptor())
                .build()
    }
}